<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="appid" prop="appid">
                <el-input v-model="queryParams.appid" placeholder="请输入appid" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
                <el-input v-model="queryParams.nickname" placeholder="请输入昵称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="订阅时间" prop="subscribeTime">
                <el-date-picker clearable v-model="queryParams.subscribeTime" type="date" value-format="yyyy-MM-dd"
                    placeholder="请选择订阅时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['wxmp:user:export']">导出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" @click="dialogTagging = true; taggingType = 'tagging'" size="small"
                    icon="el-icon-document" v-hasPermi="['wxmp:wxuser:tagging']">打标签
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" @click="dialogTagging = true; taggingType = 'unTagging'" size="small"
                    icon="el-icon-document" v-hasPermi="['wxmp:wxuser:tagging']">去除标签
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button :span="1.5" type="danger" @click="synchroWxUser" size="mini" icon="el-icon-refresh"
                    v-hasPermi="['wxmp:wxuser:synchro']">同步用户
                </el-button>
            </el-col>
            <el-dialog :title='taggingType == "tagging" ? "请选择要打的标签" : "请选择要去除的标签"' :visible.sync="dialogTagging"
                width="30%">
                <el-checkbox-group v-model="checkedTags">
                    <el-checkbox v-for="tag in userTagsData" :label="tag.id" :key="tag.id">{{ tag.name }}
                    </el-checkbox>
                </el-checkbox-group>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogTagging = false">取 消</el-button>
                    <el-button type="primary" @click="toTagging">确 定</el-button>
                </span>
            </el-dialog>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <template slot="tagidListSearch" slot-scope="scope">
            <el-select v-model="scope.row.tagidList" placeholder="请选择">
                <el-option v-for="item in userTagsData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
            </el-select>
        </template>
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="微信openid" align="center" prop="openid" />
            <el-table-column label="appid" align="center" prop="appid" />
            <el-table-column label="手机号" align="center" prop="phone" />
            <el-table-column label="昵称" align="center" prop="nickname" />
            <el-table-column label="性别" align="center" prop="sex">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.wx_sex" :value="scope.row.sex" />
                </template>
            </el-table-column>
            <el-table-column label="头像" align="center" prop="headimgurl" width="100">
                <template slot-scope="scope" v-if="scope.row.headimgurl">
                    <image-preview :src="scope.row.headimgurl" :width="50" :height="50" />
                </template>
            </el-table-column>
            <el-table-column label="订阅时间" align="center" prop="subscribeTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.subscribeTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="是否关注" align="center" prop="subscribe">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.wx_subscribe" :value="scope.row.subscribe" />
                </template>
            </el-table-column>
            <el-table-column label="分组标签" align="center">
                <template slot-scope="scope">
                    <div v-if="scope.row.tagIds">
                        <div v-for="tag in userTagsData">
                            <div v-for="id in scope.row.tagIds">
                                <div v-if="tag.id == id">
                                    <el-tag>{{ tag.name }}</el-tag>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="关注场景" align="center" prop="subscribeScene">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.wechat_subscribe_scene" :value="scope.row.subscribeScene" />
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-document" @click="remark(scope.row)"
                        v-hasPermi="['system:user:edit']">备注</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:user:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['system:user:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
            @pagination="getList" />

        <!-- 添加或修改用户对话框 -->
        <el-dialog :title="title" :visible.sync="open" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="90px">
                <el-row :gutter="15">
                    <el-col :span="7">
                        <el-form-item label="appid：" prop="appid">
                            <div>{{ form.appid }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="手机号：" prop="phone">
                            <el-input v-model="form.phone" placeholder="请输入手机号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="昵称：" prop="nickname">
                            <el-input v-model="form.nickname" placeholder="请输入昵称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="15">
                    <el-col :span="7">
                        <el-form-item label="订阅时间：" prop="subscribeTime">
                            <div>{{ form.subscribeTime }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="省份：" prop="province">
                            <el-input v-model="form.province" placeholder="请输入省份" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="城市：" prop="city">
                            <el-input v-model="form.city" placeholder="请输入城市" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="15">
                    <el-col :span="7">
                        <el-form-item label="性别：" prop="sex">
                            <div v-if="form.sex == 0">
                                <el-tag type="info">未知</el-tag>
                            </div>
                            <div v-if="form.sex == 1">
                                <el-tag type="warning">女</el-tag>
                            </div>
                            <div v-if="form.sex == 2">
                                <el-tag>男</el-tag>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="是否关注：" prop="subscribe">
                            <div v-if="form.subscribe == 0">
                                <el-tag type="warning">未关注</el-tag>
                            </div>
                            <div v-if="form.subscribe == 1">
                                <el-tag type="warning">已关注</el-tag>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="备注：" prop="remark">
                            <div>{{ form.remark }}</div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="15">
                    <el-col :span="7">
                        <el-form-item label="unionid" prop="unionid">
                            <div v-if="form.unionid">{{ form.unionid }}</div>
                            <div v-else>
                                <el-tag type="warning">暂未绑定</el-tag>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="扫码场景值" prop="qrSceneStr">
                            <div v-if="form.qrSceneStr">{{ form.qrSceneStr }}</div>
                            <div v-else>
                                <el-tag type="warning">未扫码</el-tag>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="标签列表" prop="tagidList">
                            <div v-if="form.tagIds">
                                <div v-for="tag in userTagsData">
                                    <div v-for="id in form.tagIds">
                                        <div v-if="tag.id == id">
                                            <el-tag>{{ tag.name }}</el-tag>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-form-item label="头像">
                        <image-upload v-model="form.headimgurl" :limit="limit" />
                    </el-form-item>
                </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 修改备注弹窗 -->
        <el-dialog :title="title" :visible.sync="openRemark" append-to-body width="350px">
            <el-form ref="form" :model="form" :rules="rules" label-width="50px">
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitRemark">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { listUser, getUser, delUser, synchroWxUser, addUser, updateRemark, updateUser, tagging } from "@/api/wechat/user";
import { getList as getTagList } from "@/api/wechat/wxUserTags"
export default {
    name: "User",
    dicts: ['wx_sex', 'wx_subscribe', 'wechat_subscribe_scene'],
    data() {
        return {

            // 遮罩层
            loading: true,
            limit: 1,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 用户表格数据
            userList: [],
            appid: 'wx19b4cd3f33d0c623',
            dialogTagging: false,
            checkedTags: [],
            userTags: [],
            userTagsData: [],
            selectionData: [],
            taggingType: '',
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            openRemark: false,
            disabled: false,
            // 查询参数
            queryParams: {
                current: 1,
                size: 10,
                appid: 'wx19b4cd3f33d0c623',
                phone: null,
                nickname: null,
                subscribeTime: null,
                tagidList: null,
                qrSceneStr: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                appid: [
                    { required: true, message: "appid不能为空", trigger: "blur" }
                ],
            }
        };
    },
    created() {
        this.listUserTags()
    },
    methods: {
        /** 查询用户列表 */
        getList() {
            this.loading = true;
            listUser(this.queryParams).then(response => {
                this.userList = response.data.records;
                this.total = response.data.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                openid: null,
                appid: 'wx19b4cd3f33d0c623',
                phone: null,
                nickname: null,
                sex: null,
                city: null,
                province: null,
                headimgurl: null,
                subscribeTime: null,
                subscribe: null,
                unionid: null,
                remark: null,
                tagidList: null,
                subscribeScene: null,
                qrSceneStr: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            console.log(selection)
            this.ids = selection.map(item => item.openid)
            this.single = selection.length !== 1
            this.multiple = !selection.length
            this.selectionData = selection
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加用户";
        },
        /**修改用户备注 */
        remark(row) {
            this.reset();
            const openid = row.openid || this.ids
            getUser(openid).then(response => {
                this.form = response.data;
                this.openRemark = true;
                this.title = "修改用户备注";
            });
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const openid = row.openid || this.ids
            getUser(openid).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改用户";
            });
        },
        submitRemark() {
            updateRemark(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.openRemark = false;
                this.getList();
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.openid != null) {
                        updateUser(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addUser(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const openids = row.openid || this.ids;
            this.$modal.confirm('是否确认删除用户编号为"' + openids + '"的数据项？').then(function () {
                return delUser(openids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/user/export', {
                ...this.queryParams
            }, `user_${new Date().getTime()}.xlsx`)
        },
        /**获取用户标签 */
        listUserTags() {
            this.tableLoading = true
            getTagList(this.appid).then(response => {
                if (response.code == 200) {
                    let userTagsData = response.data
                    this.userTagsData = userTagsData

                } else {
                    this.$message.error('获取用户标签出错：' + response.msg)
                }
                this.tableLoading = false
                this.getList(this.page)
            }).catch(() => {
                this.tableLoading = false
                this.getList(this.page)
            })
        },
        /**打标签/去除标签 */
        toTagging() {
            let openIdList = []
            for (const element of this.selectionData) {
                openIdList.push(element.openid)
            }
            if (this.checkedTags.length <= 0) {
                this.$message.error('请选择标签')
                return
            }
            if (openIdList.length <= 0) {
                this.$message.error('请选择用户')
                return
            }
            this.tableLoading = true
            let tagId = this.checkedTags.join(",");
            tagging({
                taggingType: this.taggingType,
                tagIds: tagId,
                tagidList: tagId,
                openIds: openIdList,
                appid: this.appid
            }).then(response => {
                this.tableLoading = false
                this.checkedTags = []
                if (response.code == 200) {
                    this.getList(this.page)
                } else {
                    this.$message.error('打标签出错：' + response.msg)
                }
            }).catch(() => {
                this.tableLoading = false
            })
            this.dialogTagging = false
        },
        selectionChange(list) {
            this.selectionData = list
        },
        searchChange(params, done) {
            params = this.filterForm(params)
            this.paramsSearch = params
            this.page.currentPage = 1
            this.getPage(this.page, params)
            done()
        },
        synchroWxUser() {
            this.$confirm('同步用户需要一定时间，用户量越大、用时越久，请耐心等待，勿重复提交；确认此操作吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.tableLoading = true
                synchroWxUser('wx19b4cd3f33d0c623').then(response => {
                    console.log(response);
                    this.tableLoading = false
                    if (response.code == 200) {
                        this.getList(this.page)
                    } else {
                        this.$message.error('同步微信用户出错：' + response.msg)
                    }
                }).catch(() => {
                    this.tableLoading = false
                })
                setTimeout(() => {
                    if (this.tableLoading) {
                        this.tableLoading = false
                        this.$alert('同步请求发送成功，系统正在处理中，请稍后刷新查看同步结果，用户量越大用时越久，请耐心等待，勿重复提交', '提示', {
                            confirmButtonText: '确定'
                        })
                    }
                }, 3000)
            }).catch(() => {
                console.log('错误');
            })
        }
    }
};
</script>

